package com.future.hedongjun.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.future.baselib.entity.BaseResponse;
import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.http.HttpRequest;
import com.future.hedongjun.R;
import com.future.hedongjun.common.MyApp;
import com.future.hedongjun.home.activity.ClassDetailActivity;
import com.future.hedongjun.home.activity.ClassListActivity;
import com.future.hedongjun.home.activity.MessageActivity;
import com.future.hedongjun.home.activity.SearchActivity;
import com.future.hedongjun.home.activity.ZhuantiClassListActivity;
import com.future.hedongjun.home.adapter.CategoryAdapter;
import com.future.hedongjun.home.adapter.TopicAdapter;
import com.future.hedongjun.home.adapter.ZhuantiAdapter;
import com.future.hedongjun.home.bean.BannerBean;
import com.future.hedongjun.home.bean.CategoryBean;
import com.future.hedongjun.home.bean.ThemeBean;
import com.future.hedongjun.home.bean.TopicBean;
import com.future.hedongjun.home.bean.response.HomeResponse;
import com.future.hedongjun.home.utils.GlideImageLoader;
import com.future.hedongjun.mall.activity.GoodsDetailActivity;
import com.future.hedongjun.mine.ui.LoginActivity;
import com.jaeger.library.StatusBarUtil;
import com.youth.banner.Banner;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import q.rorbin.badgeview.Badge;
import q.rorbin.badgeview.QBadgeView;

/**
 * @author jniu
 * @Email niuxiaoqi@hztianque.com
 * @time 2018/11/10
 */
public class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.iv_left)
    ImageView ivLeft;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_right)
    ImageView ivRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.view_line)
    View viewLine;
    @BindView(R.id.layout_title)
    FrameLayout layoutTitle;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.iv_msg)
    ImageView ivMsg;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.recycler_category)
    RecyclerView recyclerCategory;
    @BindView(R.id.recycler_zhuanti)
    RecyclerView recyclerZhuanti;
    @BindView(R.id.layout_class_more)
    FrameLayout layoutClassMore;
    @BindView(R.id.recycler_class)
    RecyclerView recyclerClass;
    Unbinder unbinder;
    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;
    private CategoryAdapter categoryAdapter;
    private List<CategoryBean> categoryBeans;
    private TopicAdapter classAdapter;
    private List<BannerBean> bannerBeans;
    private ZhuantiAdapter zhuantiAdapter;
    private Badge badge;

    public HomeFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        StatusBarUtil.setTranslucentForImageView(getActivity(), 0x30, null);
        initView();
        getData();
        return view;
    }


    private void getData() {
        new HttpRequest<HomeResponse>()
                .with(getContext())
                .setPath("/api/Index/index")
                .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        HomeResponse homeResponse = (HomeResponse) response;
                        //banner
                        banner.update(homeResponse.bannerBeans);
                        refreshLayout.setRefreshing(false);
                        //分类
                        categoryAdapter.setNewData(homeResponse.categoryBeans);
                        //专题数据
                        zhuantiAdapter.setNewData(homeResponse.themeBeans);
                        //精品课程
                        classAdapter.setNewData(homeResponse.topicBeans);
                    }
                }).start(new HomeResponse());
    }

    @Override
    public void onResume() {
        super.onResume();
//        getUnReadMsgCount();
    }

    private void getUnReadMsgCount() {
        if (MyApp.getInstance().hasLogin()) {
            new HttpRequest<DefaultResponse>()
                    .with(getContext())
                    .setApiCode("_mynoreadnews_001")
                    .addParam("userToken", MyApp.getInstance().getUserToken())
                    .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                        @Override
                        public void onSuccess(BaseResponse response) {
                            int count = 0;
                            try {
                                count = Integer.parseInt(response.data);
                            } catch (NumberFormatException e) {
                            }
                            if (badge == null) {
                                badge = new QBadgeView(getContext()).bindTarget(ivMsg).setExactMode(false).setBadgeNumber(count);
                            }else {
                                badge.setBadgeNumber(count);
                            }
                        }
                    }).start(new DefaultResponse());
        }

    }


    private void initView() {
        //初始化缓存返回键数据
        MyApp.isFlag = false;

        refreshLayout.setOnRefreshListener(this);

        ivLeft.setVisibility(View.GONE);
        tvTitle.setText("首页");
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                BannerBean bean = bannerBeans.get(position);
                switch (bean.getJump_type()) {
                    case 1:
                        Intent intent = new Intent(getActivity(), ClassDetailActivity.class);
                        intent.putExtra("id",bean.getRelation_id());
                        startActivity(intent);
                        break;
                    case 2:
                        Intent intent1 = new Intent(getActivity(), GoodsDetailActivity.class);
                        intent1.putExtra("id",bean.getRelation_id());
                        startActivity(intent1);
                        break;
                    case 3:

                        break;
                }
            }
        });
        //设置图片集合

        banner.setImages(new ArrayList<>());
        //banner设置方法全部调用完毕时最后调用
        banner.start();

//        initTestData();
        recyclerCategory.setLayoutManager(new GridLayoutManager(getContext(), 4));
        recyclerCategory.setFocusable(false);
        categoryAdapter = new CategoryAdapter(categoryBeans);
        recyclerCategory.setAdapter(categoryAdapter);
        categoryAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                CategoryBean item = categoryAdapter.getItem(position);
                ClassListActivity.launch(getContext(), item.getCate_name(), item.getCourse_cate_id(), "", 2);
            }
        });

        recyclerZhuanti.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerZhuanti.setFocusable(false);
        zhuantiAdapter = new ZhuantiAdapter(null);
        recyclerZhuanti.setAdapter(zhuantiAdapter);
        zhuantiAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ThemeBean bean = zhuantiAdapter.getData().get(position);
                if (bean.isHeader) {
                    Intent intent = new Intent(getContext(), ZhuantiClassListActivity.class);
                    intent.putExtra("id", bean.id);
                    startActivity(intent);
//                    ClassListActivity.launch(getContext(), bean.header, "", bean.id, 1);
                } else {
                    Intent intent = new Intent(getContext(), ClassDetailActivity.class);
                    intent.putExtra("id", bean.t.getCourse_id());
                    startActivity(intent);
                }
            }
        });

//        recyclerPaocha.setLayoutManager(new LinearLayoutManager(getContext()));
//        paochaAdapter = new TopicAdapter(topicBeans);
//        recyclerPaocha.setAdapter(paochaAdapter);
//
//        paochaAdapter.setOnItemClickListener(classClickListener);
//
//        recyclerChaju.setLayoutManager(new LinearLayoutManager(getContext()));
//        chajuAdapter = new TopicAdapter(topicBeans);
//        recyclerChaju.setAdapter(chajuAdapter);
//        chajuAdapter.setOnItemClickListener(classClickListener);

        recyclerClass.setLayoutManager(new GridLayoutManager(getContext(), 2));
        recyclerClass.setFocusable(false);
        classAdapter = new TopicAdapter(null);
        recyclerClass.setAdapter(classAdapter);
        classAdapter.setOnItemClickListener(classClickListener);
    }

    BaseQuickAdapter.OnItemClickListener classClickListener = new BaseQuickAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            TopicBean item = (TopicBean) adapter.getItem(position);
            Intent intent = new Intent(getContext(), ClassDetailActivity.class);
            intent.putExtra("id", item.getCourse_id());
            startActivity(intent);
        }
    };


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.tv_search, R.id.iv_msg})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_search:
                startActivity(new Intent(getContext(), SearchActivity.class));
                break;
            case R.id.iv_msg:
                if (MyApp.getInstance().hasLogin()) {
                    startActivity(new Intent(getContext(), MessageActivity.class));
                } else {
                    startActivity(new Intent(getContext(), LoginActivity.class));
                }
                break;
        }
    }

    @Override
    public void onRefresh() {
        getData();
//        refreshLayout.setRefreshing(false);
    }
}
